import React from 'react';
import {Renderer} from 'amis';
import {RendererProps} from 'amis';
import * as echarts from 'echarts';
import { getResultApi } from '../api/riskservice';
import IFrame from 'amis/lib/renderers/IFrame';

export interface LineChartRendererProps extends RendererProps {
    target?: string;
  }
  interface HeatMapState {
    compInfo: any
    data: any
    json: any
    className: string,
    heatmapInstance: any
    preview: boolean
  }
  
@Renderer({
  type: 'line-chart-renderer',
  name: 'line-chart-renderer'
})
export default class LineChartRenderer extends React.Component<LineChartRendererProps,HeatMapState> {
  static defaultProps = {
    title: '',
    subtext: '',
    dimension: '',
    dimensionName: '',
    numerical: [],
    dataset: [],
    option:{}
  };
  heatDOM: React.RefObject<HTMLDivElement> = React.createRef()
  myChart: echarts.ECharts | null = null;
  constructor(props: LineChartRendererProps) {
    super(props);
    console.log("this.props",this.props)
    this.state = {
      compInfo: null,
      data: null,
      json: null,
      className: '',
      heatmapInstance: null,
      preview: true
    }
  }

  componentDidMount() {
    this.getInstance()
    if (this.props.initFetch) {
      // this.getCustomApi();
      console.log('componentDidMount this.props.initFetch',this.props.initFetch)
    } else {
      console.log('componentDidMount this.props.initFetch 2',this.props.initFetch)
      // this.getInstance()
    }
  }
  getInstance = async () => { 
    this.myChart = echarts.init(this.heatDOM.current); 
    console.log("componentDidMount this.props", this.props.dataset);
    const params = { 
      "dataSetName": this.props.dataSetName, 
      "dimension": this.props.dimension, 
      "dimensionName": this.props.dimension, 
      "title": this.props.title, 
      "subtext": this.props.subtext, 
      "digitalItem": this.props.digitalItem 
    }; 
    try {
      const data = await getResultApi(params);
      console.log('API response:', data);
      this.setState({ data: data }, () => {
        this.buildOption();
      });
    } catch (error) {
      console.error('请求出错:', error);
    }
  };

  convertDigitalItemToSeries = (digitalItem: Array<{ name: string; chartType: string; column: string; oprate: string; yAxisIndex: number; }>) => {
    return digitalItem.map((item, index) => {
      if (!this.props.dimension || digitalItem.some(item => !item.name || !item.chartType || !item.column)) {
        return [];
      }
      return {
        name: item.name,
        type: item.chartType,
        encode: {
          x: this.props.dimension,
          y: item.column
        },
        yAxisIndex: item.yAxisIndex ?? 0
      };
    });
  }

  buildOption = () => {
    const { digitalItem } = this.props;
    const { data } = this.state;
    
    const series = this.convertDigitalItemToSeries(digitalItem);
    var option = { 
      title: { 
        text: this.props.title, 
        subtext: this.props.subtext ?? '' 
      }, 
      dataset: [ 
        { 
          source: data.data || [] // 使用接口返回的数据，如果没有则使用空数组
        } 
      ], 
      tooltip: { 
        trigger: 'axis', 
        axisPointer: { 
          type: 'cross', 
          crossStyle: { 
            color: '#999' 
          } 
        } 
      }, 
      toolbox: { 
        feature: { 
          dataView: { show: false, readOnly: false }, 
          magicType: { show: false, type: ['line', 'bar'] }, 
          restore: { show: false }, 
          saveAsImage: { show: true } 
        } 
      }, 
      legend: { 
        data: ['Evaporation', 'Precipitation', 'Temperature'] 
      }, 
      xAxis: [ 
        { 
          type: 'category', 
          axisPointer: { 
            type: 'shadow' 
          } 
        } 
      ], 
      yAxis: [ 
        { 
          type: 'value', 
          name: (this.props as any)['y-name'], 
          // min: 0, 
          // max: 500, 
          // interval: 100, 
          axisLabel: { 
            formatter: '{value} ' + (this.props as any)['y-unit']
          } 
        }, 
        { 
          
          type: 'value', 
          name: (this.props as any)['y2-name'],
          // min: 0, 
          // max: 100, 
          // interval: 10, 
          axisLabel: { 
            formatter: '{value}'  + (this.props as any)['y2-unit']
          } 
        } 
      ], 
      series: series
      // series: [
      //   {
      //     name: "预警次数",
      //     type: "line",
      //     encode: {
      //       x: "s_organization_name",
      //       y: "dataLogicKeyCount"
      //     },
      //     yAxisIndex: 0
      //   },
      //   {
      //     name: "风险数量",
      //     type: "bar",
      //     encode: {
      //       x: "s_organization_name",
      //       y: "rulename"
      //     },
      //     yAxisIndex: 0
      //   }
      // ], 
    }; 
    console.log("buildOption this.state", option);
    if (this.myChart) { 
      option && this.myChart.setOption(option); 
    } 
  };

  render() {
    // 移除 buildOption 调用，避免重复渲染
    return ( 
      <div className={`${this.state.className}`} ref={this.heatDOM} style={{ width: '100%', height: '100%', display: this.state.preview ? 'block' : 'none', minWidth: '200px', minHeight: '300px' }}  > 
      </div> 
    ) 
  }
}